<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>元素拖拽</title>
  <style>
    *{
      margin: 0;
      padding: 0;
    }
    #box{
      position: absolute;
      left: 0;
      top: 0;
      width: 200px;
      height: 100px;
      background-color: red;
    }
  
  </style>
</head>
<body>
  <div id="box">我是box</div>
  <script>
    var box = document.getElementById("box");
    
    box.onmousedown = function(event){
      event = event || window.event;
      
      //拿到元素的初始位置
      var eleX = box.offsetLeft;
      var eleY = box.offsetTop;
  
      //拿到鼠标的初始位置
      var startX = event.clientX;
      var startY = event.clientY;
      
      //针对IE,仍然存在ctrl+A选中文字 只有文字跟随鼠标移动
      //元素发生事件之后 鼠标的所有事件行为全部被捕获到该元素身上
      box.setCapture && box.setCapture();
      
      
      //mounsemove事件加在box身上不合适,一旦鼠标移动太快,就无法跟随鼠标移动
      //利用事件的冒泡
      document.onmousemove = function(event){
        event = event || window.event;
        //拿到鼠标的结束位置
        var endX = event.clientX;
        var endY = event.clientY;
        
        //距离差
        var disX = endX - startX;
        var disY = endY - startY;
        //最终获取元素的位置
        var lastX = eleX + disX;
        var lastY = eleY + disY;
        
        box.style.left = lastX + "px";
        box.style.top = lastY + "px";
      }
      
      document.onmouseup = function (){
        //解绑move事件
        document.onmousemove = document.onmouseup = null;
        
        //
        box.releaseCapture && box.releaseCapture();
      }
      
      //当点击字的时候 只有字跟着跑了.这是浏览器默认行为
      //dom0取消默认行为
      return false;
      
      //dom2事件取消默认行为
      //event.preventDefault();
    }
  
  </script>
</body>
</html>